package com.android.webcamsViewer;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;

public class WebcamList {
	// Static Attributes
	public static final String FILENAME = "webcam_list";

	private static final String TAG = "WebcamList";
	public static boolean refresh = true;
	
	// Attributes
	private List<Webcam> list = null;
	private Context context = null;

	public WebcamList(Context context) {
		this.context = context;
		list = new ArrayList<Webcam>();
		readFile();
	}

	private void readFile() {
		try {
			FileInputStream fis = context.openFileInput(FILENAME);
			BufferedReader buf = new BufferedReader(new InputStreamReader(fis));
			String line = null;
			while ((line = buf.readLine()) != null) {
				Webcam webcam = parseLine(line);
				if (webcam != null)
					list.add(webcam);
			}
			fis.close();
		} catch (Exception e) {
			Log.e(TAG, "Error when webcam_list file was been parsed", e);
		}
	}

	private Webcam parseLine(String line) {
		String[] elements = line.split("\\{\\{=\\}\\}");
		if (elements.length > 1) {
			String name = elements[0];
			String url = elements[1];
			return new Webcam(name, url);
		}
		return null;
	}

	private void writeFile() {
		try {
			refresh = true;
			FileOutputStream fos = context.openFileOutput(FILENAME,
					Context.MODE_PRIVATE);
			String line = "";
			for (Object element : list.toArray()) {
				Webcam webcam = (Webcam) element;
				line = webcam.toString().concat("\n");
				fos.write(line.getBytes());
			}
			fos.close();

		} catch (Exception e) {
			Log.e(TAG, "Error when webcam_list file was been writed", e);
		}
	}
	
	public void reset(){
		if(refresh) {
			refresh = false;
			list.clear();
			readFile();
		}
	}

	public void createWebcam(String name, String url) {
		Webcam webcam = new Webcam(name, url);
		list.add(webcam);
		writeFile();
	}
	
	public void updateWebcam(int position, String name, String url) {
		list.get(position).setName(name);
		list.get(position).setUrl(url);
		writeFile();
	}

	public void removeWebcam(int position) {
		if (position < list.size()) {
			list.remove(position);
			writeFile();
		}
	}

	public Webcam getWebcam(int position) {
		if (position < this.list.size()) {
			return this.list.get(position);
		}
		return null;
	}

	public int getLength() {
		return this.list.size();
	}
	
}
